<template>
  <div class="main">
    <a-space class="content" direction="vertical" align="center">
      <a-qrcode value="http://www.antdv.com" :status="Status" />
      <a-input readonly style="text-align: center;" v-model:value="text" placeholder="-" :maxlength="60" />
    </a-space>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, onActivated} from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from "@/store/userInfo";
// @ts-ignore
import SockJS from "sockjs-client/dist/sockjs.min.js";
import Stomp from 'webstomp-client';

const router = useRouter();
const authStore = useAuthStore();
const text = ref<string>('请使用微信扫码登录');
let Status = ref<string>('active')

let stompClient: any = null;
let timeoutId: number | null = null;
// 建立连接并订阅消息
const connect = () => {
  console.log('开始监听手机登录...')
  // 使用SockJS与服务器端点"/ws"建立连接
  const socket = new SockJS('http://localhost:8180/ws');
  console.log("建立了连接")
  stompClient = Stomp.over(socket);
  console.log('stompclient建立')
  stompClient.connect({}, (frame: any) => {
    console.log('Connected: ' + frame);

    // 订阅"/topic/loginStatus"主题
    stompClient.subscribe('/sms', (message: any) => {
      // 当接收到消息时，更新loginStatusMessage
      let data = JSON.parse(message.body);
      console.log("Received message:", message.body);
      console.log("data = ", data);
      authStore.login(data.userId, data.userName, data.password, data.userType, data.userEmail, data.phoneNumber, data.avatarUrl);
      router.push('/home')
    });
  }, (error: any) => {
    console.log('Connection error:', error);
  });

  // 设置60秒后断开连接
  timeoutId = window.setTimeout(() => {
    disconnect();
    Status.value = 'invalid';
  }, 60000);
}

// 断开连接
const disconnect = () => {
  if (stompClient !== null) {
    stompClient.disconnect();
    console.log("Disconnected");
  }

  if (timeoutId !== null) {
    clearTimeout(timeoutId);
    timeoutId = null;
  }
}

onUnmounted(() => {
  disconnect();
});

onActivated(()=>{
  if(timeoutId === null){
      Status.value = 'active';
      connect();
  }
})
</script>

<style scoped lang="less">
.main {
  height: 80%;
  width: 80%;
  background-color: bisque;
  display: flex;
  justify-content: center;
  align-items: center;

  .content {
    width: 80%;
    height: 80%;
  }
}
</style>